package com.example.cloud.service.business.medical.impl;

import com.example.cloud.dao.business.medical.LifeCareAdviceRepository;
import com.example.cloud.model.business.medical.LifeCareAdvice;
import com.example.cloud.service.business.medical.LifeCareAdviceService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by wangtao on 2018/6/6.
 */
@Service
public class LifeCareAdviceServiceImpl implements LifeCareAdviceService {

    private static final Logger logger = Logger.getLogger(LifeCareAdviceServiceImpl.class);

    @PersistenceContext
    EntityManager em;

    @Autowired
    private LifeCareAdviceRepository lifeCareAdviceRepository;

    @Override
    public LifeCareAdvice findOne(Long id) {
        return lifeCareAdviceRepository.findOne(id);
    }

    @Override
    public List<LifeCareAdvice> findByPatientId(Long patientId) {
        return lifeCareAdviceRepository.findByPatientIdAndDeleteFlag(patientId,0);
    }

    @Override
    @Transactional
    public void doSave(LifeCareAdvice record) {
        if(record.getId() == null){
            record.setAccountId(RequestUtil.getLoginUser().getAccountId());
        }
        BusinessUtil.appendRecord(record);
        lifeCareAdviceRepository.save(record);
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        lifeCareAdviceRepository.deleteByIdIn(ids);
    }

    @Override
    @Transactional
    public void doAddSupplement(Long id, String supplementAdvice) {
        StringBuilder sql = new StringBuilder("update life_care_advice set supplement_advice = :supplementAdvice where id = :id");
        Query nativeQuery = em.createNativeQuery(sql.toString());
        nativeQuery.setParameter("supplementAdvice", supplementAdvice);
        nativeQuery.setParameter("id", id);
        nativeQuery.executeUpdate();
    }
}
